package handler

import (
	"encoding/json"
	"github.com/gin-gonic/gin"
	"practice-hub/cache"
	"practice-hub/model"
	"strconv"
	"time"
)

func AddRepo(c *gin.Context) {
	repo_code := c.PostForm("repo_code")
	repo_name := c.PostForm("repo_name")
	repo := model.Repo{
		RepoCode: repo_code,
		RepoName: repo_name,
	}
	err := model.DB.Create(&repo).Error
	if err != nil {
		c.JSON(200, gin.H{"code": 500, "msg": "添加失败"})
		return
	}
	c.JSON(200, gin.H{"code": 200, "msg": "添加成功"})
	return
}
func AddRoleOrder(c *gin.Context) {
	order_code := c.PostForm("order_code")
	order_num, _ := strconv.Atoi(c.PostForm("order_num"))
	order_price, _ := strconv.Atoi(c.PostForm("order_price"))
	rid, _ := strconv.Atoi(c.PostForm("rid"))
	order := model.RepoOrder{
		OrderCode:  order_code,
		OrderNum:   order_num,
		OrderPrice: order_price,
		Rid:        rid,
	}
	err := model.DB.Create(&order).Error
	if err != nil {
		c.JSON(200, gin.H{"code": 500, "msg": "添加失败"})
		return
	}
	c.JSON(200, gin.H{"code": 200, "msg": "添加成功"})
	return
}
func RoleOrderList(c *gin.Context) {
	page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
	size, _ := strconv.Atoi(c.DefaultQuery("size", "5"))
	offset := (page - 1) * size
	var repo []model.RepoOrderList
	redis_key := "data_page" + strconv.Itoa(page)
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheData == "" {
		model.DB.Table("repo_orders").
			Select("repo_orders.id AS OrderId",
				"order_code AS OrderCode",
				"order_num AS OrderNum",
				"order_price AS OrderPrice",
				"repo_code AS RepoCode",
				"repo_name AS RepoName").
			Joins("LEFT JOIN repos ON repos.id = repo_orders.rid").
			Offset(offset).Limit(size).Debug().Find(&repo)
		jsonData, _ := json.Marshal(&repo)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheData), &repo)
	}
	var total int64
	model.DB.Model(&model.RepoOrder{}).Count(&total)
	c.JSON(200, gin.H{"code": 200, "msg": "查询成功", "data": repo})
	return
}
